import { defineStore } from "pinia";
import { getCurrentUserInfo, updateUserProfile as updateUserProfileApi } from "../request/api/user";

export const useUserStore = defineStore('user', {
	state: () => ({
		info: {}, // 用户信息
	}),
	actions: {
		/**
		 * 存储数据
		 * @param {Object} data
		 */
		hold(data) {
			this.info = data
		},
		/**
		 * 清空数据
		 */
		clear() {
			this.info = {}
		},
		/**
		 * 刷新用户数据
		 */
		refreshUserInfo() {
			return new Promise((resolve, reject) => {
				getCurrentUserInfo().then(data => {
					this.hold(data)
					resolve(this.info)
				}).catch(({ code = -1, message = '刷新数据失败' }) => {
					reject({ code, message })
				})
			})
		},
		/**
		 * 加载用户信息
		 */
		loadUserInfoIfNecessary() {
			if (this.info) return Promise.resolve(this.info)
			return this.refreshUserInfo()
		},
		/**
		 * 保存用户信息
		 * @param {Object} data
		 */
		updataUserProfile({ id, nickname, gender, phone, email }) {
			if (!id) return Promise.reject({ code: -1, message: '参数错误' })
			if (!nickname || !phone) return Promise.reject({ code: -1, message: '昵称、电话不能为空' })
			return updateUserProfileApi({ id, nickname, gender, phone, email }).then(data => {
				this.hold(data)
				return Promise.resolve(this.info)
			})
		}
	}
})